using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using OfficeLaunch.SharePoint.TwitterMap.TimerJobs;

namespace OfficeLaunch.SharePoint.TwitterMap.Features.TimerJob
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("f492e0b8-a2fd-454c-b8c8-07ec0f465f23")]
    public class TimerJobEventReceiver : SPFeatureReceiver
    {
        private const string JobName = "GetTweets";

        public override void FeatureActivated(SPFeatureReceiverProperties Properties)
        {
            var webApplication = Properties.Feature.Parent as SPWebApplication;
            if (webApplication == null) return;

            foreach (var jobDefinition in webApplication.JobDefinitions.Where(JobDefinition => JobDefinition.Name == JobName))
            {
                jobDefinition.Delete();
            }

            var tweetsJob = new GetTweets(JobName, webApplication)
            {
                Schedule = new SPMinuteSchedule()
                {
                    BeginSecond = 1,
                    EndSecond = 59,
                    Interval = 1
                }
            };
            tweetsJob.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties Properties)
        {
            var webApplication = Properties.Feature.Parent as SPWebApplication;
            if (webApplication == null) return;

            foreach (var jobDefinition in webApplication.JobDefinitions.Where(JobDefinition => JobDefinition.Name == JobName))
            {
                jobDefinition.Delete();
            }
        }
    }
}
